<?php

use App\Models\Sys\Permission;
use App\Models\Sys\Role;
use App\Models\Sys\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        if (!$user = User::where('username', 'admin')->first())
        {
            $user = User::create([
                'username'   => 'admin',
                'password'   => Hash::make('admin888'),
                'name'       => 'Bobby',
                'mobile'     => '15680056616',
                'email'      => 'ziee@qq.com',
                'avatar_url' => '',
                'enabled'    => true
            ]);
        }

        if (!$role = Role::where('name', 'administrator')->first())
        {
            $role = Role::create([
                'name'       => 'administrator',
                'label'      => '超级管理员',
                'desc'       => '用于系统初始化及维护',
                'guard_name' => 'admin',
                'type'       => 'ADMIN'
            ]);
        }

        $permissions = [
            ['name' => 'system-permission-get', 'label' => '系统-权限-获取',],
            ['name' => 'system-permission-create', 'label' => '系统-权限-创建',],
            ['name' => 'system-permission-update', 'label' => '系统-权限-更新',],
            ['name' => 'system-permission-delete', 'label' => '系统-权限-删除',],
            ['name' => 'system-permission-sync', 'label' => '系统-权限-角色授权',],
            ['name' => 'system-role-get', 'label' => '系统-角色-获取',],
            ['name' => 'system-role-create', 'label' => '系统-角色-创建',],
            ['name' => 'system-role-update', 'label' => '系统-角色-更新',],
            ['name' => 'system-role-delete', 'label' => '系统-角色-删除',],
            ['name' => 'system-role-sync', 'label' => '系统-角色-用户授权',],
            ['name' => 'system-user-get', 'label' => '系统-用户-获取',],
            ['name' => 'system-user-create', 'label' => '系统-用户-创建',],
            ['name' => 'system-user-update', 'label' => '系统-用户-更新',],
            ['name' => 'system-user-delete', 'label' => '系统-用户-删除',],
            ['name' => 'system-log-get', 'label' => '系统-日志-获取',],
        ];

        foreach ($permissions as $row)
        {
            if (!$permission = Permission::where('name', $row['name'])->first())
            {
                $permission = Permission::create([
                    'name'       => $row['name'],
                    'label'      => $row['label'],
                    'desc'       => '',
                    'guard_name' => 'admin',
                ]);
            }

            $role->givePermissionTo($permission->id);
        }

        $user->syncRoles($role->id);
    }
}
